
import mitt from "mitt";
let metaName:Record<string, { cached: boolean, fetching: boolean, data: any }> = {}
const emitter = mitt();
const event: Record<string, string> = {
    pageReady: "metaNameReady",
}

export function getMetaNameDictById(id: number,value:string): Promise<any> {
    return new Promise((resolve,reject) => {
        getAllMetaNamsByTableId(id).then((data: any[]) => {
            resolve(data.find((item: any) => item.value == value));
        }).catch(() => {
            reject({});
        });
    });
}

export function getAllMetaNamsByTableId(tableId:number): Promise<any> {
    if(!metaName[tableId]){
        metaName[tableId] = { cached: false, fetching: false, data: {} };
    }
    if (metaName[tableId].cached) {
        return new Promise((resolve) => {
            resolve(metaName[tableId].data);
        });
    }
    if (metaName[tableId].fetching) {
        return new Promise((resolve) => {
            emitter.on(event.pageReady, () => {
                resolve(metaName[tableId].data);
            })
            if (metaName[tableId].cached) {
                resolve(metaName[tableId].data);
            }
        });
    }
    metaName[tableId].fetching = true;
    const url = '/biz/form/names';
    return new Promise((resolve, reject) => {
        window.$theia.http
            .post(url, {table_id:tableId})
            .then((response: any) => {
                metaName[tableId].cached = true;
                metaName[tableId].fetching = false;
                metaName[tableId].data = response;
                emitter.emit(event.pageReady);
                resolve(response);
            })
            .catch((err: any) => {
                metaName[tableId].fetching = false;
                reject(err);
            });
    });
}